package org.example.api.transform;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;
import org.example.api.bean.SensorReading;

import java.util.Collections;

/**
 * @author huangqihan
 * @date 2021/2/19
 */
public class TransformToMultipleStreams {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> inputStream = env.readTextFile("src/main/resources/sensor.txt");

        SingleOutputStreamOperator<SensorReading> mapStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // 1.split
        SplitStream<SensorReading> splitStream = mapStream.split(
                data -> data.getTemperature() > 30 ? Collections.singletonList("high") : Collections.singletonList("low")
        );
        DataStream<SensorReading> high = splitStream.select("high");
        DataStream<SensorReading> low = splitStream.select("low");

        high.print("high");
        low.print("low");

        // 2.connect
        SingleOutputStreamOperator<Tuple2<String, Double>> warningStream = high.map(
                new MapFunction<SensorReading, Tuple2<String, Double>>() {
                    @Override
                    public Tuple2<String, Double> map(SensorReading s) {
                        return new Tuple2<>(s.getId(), s.getTemperature());
                    }
                }
        );

        ConnectedStreams<Tuple2<String, Double>, SensorReading> connectStreams = warningStream.connect(low);
        SingleOutputStreamOperator<Object> resultStream = connectStreams.map(
                new CoMapFunction<Tuple2<String, Double>, SensorReading, Object>() {
                    @Override
                    public Object map1(Tuple2<String, Double> t) {
                        return new Tuple3<>(t.f0, t.f1, "high temperature warning");
                    }

                    @Override
                    public Object map2(SensorReading s) {
                        return new Tuple2<>(s.getId(), "normal");
                    }
                }
        );

        resultStream.print();

        // 3.union (need the same data type)
        // warningStream.union(low);

        env.execute();

    }
}
